﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;

using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraVerticalGrid.Events;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Aksesuar
{
    public partial class Stok : XForm
    {
        public Stok()
        {
            InitializeComponent();
        }
        BindingSource bsAksesuarStok;
        private void Stok_Load(object sender, EventArgs e)
        {
            
            bsAksesuarStok = gvAksesuarStok.Init("GetAksesuarStok",0,0,0,"",0,0,"","","","",WhoAmI);
            gvAksesuarStok.AddDetailGrid(gvAksesuarAyrim, "AksesuarId");


            gvAksesuarStok.Columns["AksesuarId"].ColumnEdit = new RepositoryItemTextEdit();
            gvAksesuarStok.Columns["AksesuarId"].OptionsColumn.AllowEdit = false;
            gvAksesuarStok.Columns["AksesuarId"].AppearanceCell.BackColor = System.Drawing.Color.LightYellow;

            gvAksesuarStok.AddColumn("QtySelected", typeof(int), "Sum(Child({FK}).QtySelected)");

            gvAksesuarAyrim.MakeColumnInvisible("ScA", "AksesuarId", "AyrimId", "HoldFor");

            gvAksesuarStok.FormatAsNumber(0, "Qty", "QtySelected");
            gvAksesuarStok.AddSummary("Qty", "QtySelected");

            gvAksesuarStok.SetCaptions("Qty:Stok Miktarı", "QtySelected:Seçilen Miktar");
            gvAksesuarAyrim.SetCaptions("Qty:Stok Miktarı", "QtySelected:Seçilen Miktar");

            gvAksesuarAyrim.FormatAsNumber(0, "Qty","QtySelected");
            gvAksesuarAyrim.AddSummary("Qty", "QtySelected");

            gvAksesuarStok.MakeReadOnly();
            gvAksesuarAyrim.MakeReadOnly("QtySelected");

            GridManager gm = GridManager.GetManager(gvAksesuarStok);
            gm.GridMenu.AddMenu("Seçili aksesuarların IDLE miktarlarını seç",SelectIdle);
            gm.GridMenu.AddMenu("Seçili aksesuarların IDLE miktarlarını bırak", UnselectIdle);
            gm.GridMenu.AddMenu("Seçili aksesuarların TÜM miktarlarını seç",SelectAll);
            gm.GridMenu.AddMenu("Seçili aksesuarların TÜM miktarlarını bırak",UnselectAll);
            gm.GridMenu.AddMenu("Stok Hareketleri", gvAksesuarStok_DoubleClick);

            gvAksesuarAyrim.RowCellStyle += gvAksesuarAyrim_RowCellStyle;
            gvAksesuarAyrim.CellValueChanged += gvAksesuarAyrim_CellValueChanged;
            gvAksesuarStok.RowStyle += gvAksesuarStok_RowStyle;
            btnGetir.Click += btnGetir_Click;
            btnTemizle.Click += btnTemizle_Click;
            gvAksesuarStok.DoubleClick += gvAksesuarStok_DoubleClick;

            splitContainerControl1.AutoSize();
            gvAksesuarStok.BestFitColumns();
            gvAksesuarAyrim.BestFitColumns();

            CreateVerticalGrid();

            gvAksesuarStok.OptionsView.EnableAppearanceEvenRow = gvAksesuarStok.OptionsView.EnableAppearanceOddRow = false;
            //gvAksesuarStok.Appearance.OddRow.BackColor = Color.WhiteSmoke;
        }

        void gvAksesuarStok_DoubleClick(object sender, EventArgs e)
        {

            int handle = gvAksesuarStok.FocusedRowHandle;

            if (handle > -1)
            {
                int AksesuarId = intParse(gvAksesuarStok.GetRowCellValue(handle, "AksesuarId"));
                using (AksesuarHareketGC ah = new AksesuarHareketGC(AksesuarId, null, null))
                    ah.ShowDialog();
            }
        
        }

        private void UnselectAll(object sender, EventArgs e)
        {
            string AksesuarIds = gvAksesuarStok.GetSelectedValues("AksesuarId");
            foreach (string AksesuarId in AksesuarIds.Split(','))
            {
                foreach (DataRow dr in gvAksesuarAyrim.DataTable().Select("AksesuarId = " + AksesuarId))
                {
                    string HoldFor = dr["HoldFor"].ToStr();
                    if (HoldFor == "")
                    {
                        dr["QtySelected"] = DBNull.Value;
                    }
                }
            }
        }

        private void SelectAll(object sender, EventArgs e)
        {
            string AksesuarIds = gvAksesuarStok.GetSelectedValues("AksesuarId");
            foreach (string AksesuarId in AksesuarIds.Split(','))
            {
                foreach (DataRow dr in gvAksesuarAyrim.DataTable().Select("AksesuarId = " + AksesuarId))
                {
                    string HoldFor = dr["HoldFor"].ToStr();
                    if (HoldFor == "")
                    {
                        dr["QtySelected"] = dr["Qty"];
                    }
                }                
            }
        }

        private void UnselectIdle(object sender, EventArgs e)
        {
            string AksesuarIds = gvAksesuarStok.GetSelectedValues("AksesuarId");
            foreach (string AksesuarId in AksesuarIds.Split(','))
            {
                    //int AksesuarId = gvAksesuarStok.GetRowCellValue(RowHandle, "AksesuarId").ToInt();
                foreach (DataRow dr in gvAksesuarAyrim.DataTable().Select("AksesuarId = " + AksesuarId))
                {
                    string HoldFor = dr["HoldFor"].ToStr();
                    string OrderRef = dr["OrderRef"].ToStr();
                    if (HoldFor == "" && OrderRef == "")
                    {
                        dr["QtySelected"] = DBNull.Value;
                    }
                }
            }
        }

        private void SelectIdle(object sender, EventArgs e)
        {
            string AksesuarIds = gvAksesuarStok.GetSelectedValues("AksesuarId");
            foreach (string AksesuarId in AksesuarIds.Split(','))
            {
                foreach (DataRow dr in gvAksesuarAyrim.DataTable().Select("AksesuarId = " + AksesuarId))
                {
                    string HoldFor = dr["HoldFor"].ToStr();
                    string OrderRef = dr["OrderRef"].ToStr();
                    if (HoldFor == "" && OrderRef == "")
                    {
                        dr["QtySelected"] = dr["Qty"];
                    }
                }
            }
        }

        private void CreateVerticalGrid()
        {
            vgc.Rows.AddRange(new BaseRow[] {
                AddItem("Musteri", typeof(int), RI(Rp.V_Customer)),
                AddItem("Marka", typeof(int), RI(Rp.Brand)),
                AddItem("Sezon", typeof(int), RI(Rp.Sezon)),
                AddItem("OrderRef", typeof(string)),
                AddItem("Kategori", typeof(int), RI(Rp.ProductCategory)),
                AddItem("Aksesuar", typeof(int), RI(Rp.V_Aksesuar)),
                AddItem("Renk", typeof(string)),
                AddItem("Etiket", typeof(string)),
                AddItem("Boy", typeof(string)),
                AddItem("Aciklama", typeof(string))
            });

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;
            vgc.BestFit();
        }

        public BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }


        void gvAksesuarStok_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (((GridView)sender).GetRowCellValue(e.RowHandle, "QtySelected").ToDecimal() > 0)
                e.Appearance.BackColor = Color.LightBlue;
            else
                e.Appearance.Combine((e.RowHandle & 1) != 0 ? gvAksesuarStok.Appearance.EvenRow : gvAksesuarStok.Appearance.OddRow);
        }

        void gvAksesuarAyrim_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                string HoldFor = gvAksesuarAyrim.GetFocusedRowCellValue("HoldFor").ToStr();
                int Qty = gvAksesuarAyrim.GetFocusedRowCellValue("Qty").ToInt();
                int QtySelected = gvAksesuarAyrim.GetFocusedRowCellValue("QtySelected").ToInt();

                if (HoldFor == "")
                {
                    if (QtySelected > Qty)
                    {
                        if (Qty < 0)
                        {
                            gvAksesuarAyrim.CellValueChanged -= gvAksesuarAyrim_CellValueChanged;
                            ShowErrorMessage("Stok miktarı yetersiz !");
                            gvAksesuarAyrim.SetFocusedRowCellValue("QtySelected", null);
                            gvAksesuarAyrim.CellValueChanged += gvAksesuarAyrim_CellValueChanged;
                            return;
                        }

                        gvAksesuarAyrim.CellValueChanged -= gvAksesuarAyrim_CellValueChanged;
                        if (XtraMessageBox.Show("Seçebileceğiniz miktar en fazla " + Qty.ToString() + "  adettir.  " + Qty.ToString() + " adet seçmek ister misiniz ?", "Critical", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                            gvAksesuarAyrim.SetFocusedRowCellValue("QtySelected", Qty);
                        else
                            gvAksesuarAyrim.SetFocusedRowCellValue("QtySelected", null);
                        gvAksesuarAyrim.CellValueChanged += gvAksesuarAyrim_CellValueChanged;
                        return;
                    }
                }
                else
                {
                    if (!(MyDept == 1 && HoldFor == "C"))
                    {
                        gvAksesuarAyrim.CellValueChanged -= gvAksesuarAyrim_CellValueChanged;
                        ShowErrorMessage("Askıda olan aksesuardan çıkış ya da istek yapamazsınız !");
                        gvAksesuarAyrim.SetFocusedRowCellValue("QtySelected", null);
                        gvAksesuarAyrim.CellValueChanged += gvAksesuarAyrim_CellValueChanged;
                        return;
                    }
                }
            }
        }

        void gvAksesuarAyrim_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
            {
                string HoldFor = gvAksesuarAyrim.GetRowCellValue(e.RowHandle, "HoldFor").ToStr();
                switch (e.Column.FieldName)
                {
                    case "Qty":
                        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                        if (HoldFor != "")
                            e.Appearance.ForeColor = Color.Red;
                        return;
                }
            }
        }

        private void bbiAyir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvAksesuarAyrim.EndEditing();
            DataRow[] drSecilenAksesuarlar = gvAksesuarAyrim.DataTable().Select("Isnull(QtySelected,0) > 0");
            DataRow[] drSecilenOrtakAksesuarlar = gvAksesuarAyrim.DataTable().Select("BrandId = 1 and Isnull(QtySelected,0) > 0");

            if (drSecilenAksesuarlar.Length == 0)
            {
                ShowErrorMessage("Lütfen transfer yapacağınız aksesuarların miktarlarını girin !");
                return;
            }
            else if (drSecilenOrtakAksesuarlar.Length > 0)
            {
                ShowErrorMessage("Ortak aksesuarlara ayrım yapamazsınız !");
                return;
            }
            else
            {
                DataTable dt = drSecilenAksesuarlar.CopyToDataTable();
                dt.TableName = "Aksesuar";

                using (AksesuarTransfer transfer = new AksesuarTransfer(dt))
                {
                    if (transfer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        Yenile(); 
                }
            }
        }

        private void btnGetir_Click(object sender, EventArgs e)
        {
            Yenile();            
        }

        private void Yenile()
        {
            gvAksesuarStok.RefreshDataSource(true, "GetAksesuarStok",
            GetVal("Musteri").ToInt(),
            GetVal("Marka").ToInt(),
            GetVal("Sezon").ToInt(),
            GetVal("OrderRef").ToStr(),
            GetVal("Kategori").ToInt(),
            GetVal("Aksesuar").ToInt(),
            GetVal("Renk").ToStr(),
            GetVal("Etiket").ToStr(),
            GetVal("Boy").ToStr(),
            GetVal("Aciklama").ToStr(),
            WhoAmI);
        }

        private void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);
        }

        private void bbiCikis_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvAksesuarAyrim.EndEditing();
            gvAksesuarStok.EndEditing();
            DataRow[] drSecilenAksesuarlar = gvAksesuarAyrim.DataTable().Select("Isnull(QtySelected,0) > 0");

            int KoliKutuAdedi = gvAksesuarStok.DataTable().Select("ISNULL(QtySelected,0)>0 and ProductCategoryId in (29,41,117)").Length;
            int SecilenAksesuarlar = gvAksesuarStok.DataTable().Select("ISNULL(QtySelected,0)>0 ").Length;
            int TalepEdilenAksesuar = drSecilenAksesuarlar.Length;
            if (SecilenAksesuarlar > KoliKutuAdedi && KoliKutuAdedi > 0)
            {
                XtraMessageBox.Show("Aynı talepte hem aksesuar hem de koli-kutu çıkışı yapamazsınız. Koli-kutu çıkışı için ayrı bir talep oluşturun !");
                return;
            }

            if (drSecilenAksesuarlar.Length == 0)
            {
                ShowErrorMessage("Lütfen çıkış yapacağınız aksesuarların miktarlarını girin !");
                return;
            }
            else
            {
                DataTable dt = drSecilenAksesuarlar.CopyToDataTable();
                dt.TableName = "Table";
                
                DataTable dtEmpCustomer = gvAksesuarStok.Dataset().Tables[2];
                string Brands = dtEmpCustomer.GetValuesofSpecifiedColumn("BrandId",",");

                DataRow[] drNotBrand = dt.Select(string.Format("BrandId not in ({0})",Brands));

                if (drNotBrand.Length > 0)
                {
                    string AksesuarHata = "Aşağıdaki aksesuarları çıkmak için ilk önce kendi markanıza ayırmanız gerekmektedir.\n\n";
                    foreach (DataRow dr in drNotBrand)
                    {
                        string Marka = AppSession.Lookups.Brand.FindByBrandId(dr["BrandId"].ToInt()).Name;
                        string StokKod = AppSession.Lookups.V_Aksesuar.FindByAksesuarId(dr["AksesuarId"].ToInt()).StokKod;
                        AksesuarHata += Marka + " - " + StokKod + "\n";
                    }

                    ShowErrorMessage(AksesuarHata);
                    return;
                }
                else
                {
                    DataTable dtTransfer = drSecilenAksesuarlar.CopyToDataTable();
                    dtTransfer.TableName = "Aksesuar";

                    dt.Columns["QtySelected"].ColumnName = "TalepEdilen";
                    string Changes = dt.Serialize();

                    using (AksesuarCikisTalebi ac = new AksesuarCikisTalebi(Changes, dtTransfer, true))
                        if (ac.ShowDialog() == DialogResult.OK)
                            Yenile();                      
                }

            }
        }

        private void bciSecilen_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bsAksesuarStok.Filter = bciSecilen.Checked ? "Isnull(QtySelected,0) > 0" : "";
        }

    }
}
